#include "graph.h"

#include "titlebar.h"

widget_t *create_title_bar(widget_t *parent, int32_t x, int32_t y,
    uint32_t width, uint32_t height)
{
    // create the widget
    widget_t *self = create_widget(parent, x, y, width, height, TRUE);
    // create memory for extern information
    self->ext = malloc(sizeof(title_bar_t));
    ((title_bar_t *)self->ext)->pressed = FALSE;
    // bind the callback function
    callback_t *callback = self->callback;
    callback->paint = title_bar_paint;
    callback->lbutton_down = title_bar_lbutton_down;
    callback->mouse_move = title_bar_mouse_move;
    callback->lbutton_up = title_bar_lbutton_up;
    callback->free = title_bar_free;
    // return a pointer to the widget
    return self;
}

void title_bar_paint(widget_t *self, HDC hdc)
{
    RECT rect;
    GetClientRect(self->hwnd, &rect);
    // fill the background with a light blue color
    rgb_t dark_blue = {180,40,40};
    rgb_t light_blue = {255,130,130};
    vert_gradient_rect(self, &rect, dark_blue, light_blue);
    // draw the text as white
    SetTextColor(hdc, RGB(255,255,255));
    SetBkMode(hdc, TRANSPARENT);
    rect.left += 5; // set margin of 5 pixel to the left edge
    DrawText(hdc, self->parent->text, -1, &rect, DT_VCENTER|DT_SINGLELINE);
}

void title_bar_lbutton_down(widget_t *self, int32_t x, int32_t y,
    uint32_t flag)
{
    title_bar_t *ext = self->ext;
    // save the mouse coordinate
    GetCursorPos(&ext->mouse_ref);
    // save the parent widget coordinate and size
    GetWindowRect(self->hwnd, &ext->parent_ref);
    // capture mouse position when the outside the tile bar client area
    SetCapture(self->hwnd);
    // marked that the widget have been pressed
    ext->pressed = TRUE;
}

void title_bar_mouse_move(widget_t *self, int32_t x, int32_t y,
    uint32_t flag)
{
    title_bar_t *ext = self->ext;
    // move the window if its been pressed
    if(ext->pressed == TRUE)
    {
        widget_t *parent = self->parent;
        POINT point;    
        GetCursorPos(&point);
        // calculate the new coordinates for the window
        int wx = ext->parent_ref.left + (point.x - ext->mouse_ref.x);
        int wy = ext->parent_ref.top + (point.y - ext->mouse_ref.y);
        // move the window to the new coordinates
        MoveWindow(parent->hwnd, wx, wy, parent->width, parent->height, TRUE);
    }
}

void title_bar_lbutton_up(widget_t *self, int32_t x, int32_t y,
    uint32_t flag)
{
    // mark that the button have been released
    ((title_bar_t *)self->ext)->pressed = FALSE;
    // stop capture the mouse position
    ReleaseCapture();
}

void title_bar_free(widget_t *self)
{
    free(self->ext);
    free(self);
}

